<!doctype html>
<!--[if lt IE 7]>
<html lang="en-US" class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>
<html lang="en-US" class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>
<html lang="en-US" class="no-js lt-ie9""> <![endif]-->
<!--[if gt IE 8]><!-->
<html lang="en-US" class="no-js"> <!--<![endif]-->
<head>
    <title>PINPOINT</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate" />
	<meta http-equiv="expires" content="0" />
	<meta http-equiv="pragma" content="no-cache" />
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <link rel="shortcut icon" href="favicon.png" type="image/png">
    <link rel="icon" href="favicon.png" type="image/png">
    <link rel="stylesheet" href="components/bootstrap/dist/css/bootstrap.min.css?v=${buildTime}">
    <link rel="stylesheet" href="styles/timer.css?v=${buildTime}">
    <style>
		.starter-template {
		  padding: 40px 15px;
		  text-align: center;
		}
		path {  stroke: #fff; }
		path:hover {  opacity:0.9; }
		rect:hover {  fill:blue; }
		.axis {  font: 10px sans-serif; }
		.legend tr{    border-bottom:1px solid grey; }
		.legend tr:first-child{    border-top:1px solid grey; }
		
		.axis path,
		.axis line {
		  fill: none;
		  stroke: #000;
		  shape-rendering: crispEdges;
		}
		
		.x.axis path {  display: none; }
		.legend{
		    display:inline-block;
		    border-collapse: collapse;
		    border-spacing: 0px;
		}
		.legend td{
		    padding:4px 5px;
		    vertical-align:bottom;
		}
		.legendFreq, .legendPerc{
		    align:right;
		    width:50px;
		}
		.main-navbar {
		    position: absolute;
		    margin: 0px 0 0 0;
		    height: 40px;
		    min-height: 40px;
		    background-color: #252a3a;
		    width: 100%;
		    border-radius: 0px;
		}
		.main-navbar .navbar-brand {
			padding: 7px 15px;
		}
		.navbar .beta {
		    position: absolute;
		    left: 138px;
		    top: 12px;
		    font-size: 12px;
		    color: rgb(216, 33, 33);
		}
		.loading {
			position:absolute;
			top: 0px;
			width:100%;
			height:100%;
			background: rgba(255, 255, 255, .5);
			text-align:center;
		}		
				
    </style>
</head>
<body>
	<div class="navbar main-navbar bs-docs-nav">
		<div class="nav-container">
			<a href="/" class="navbar-brand"><img class="brand" src="images/logo2.png" width="116" height="18"><div class="beta">beta</div></a>
		</div>
	</div>

	<div class="container">
  		<div class="starter-template">
    		<h1>Pinpoint Agent Version Statistic</h1>
    		<div id='dashboard' style="display:inline-block;padding-right: 10px;"></div>
			<div id='jvmDashboard' style="display:inline-block"></div>
  		</div>
  		<div>
			<select class="form-control" id="filter-version">
				<option value="all" selected>All</option>
			</select>
		</div>
  		<table class="table table-striped" id="versionList">
  			<thead>
  				<tr>
  					<th>#</th>
  					<th>Application</th>
  					<th>Agent</th>
  					<th>Version</th>
					<th>JVM Version</th>
  				</tr>
  			</thead>
  			<tbody></tbody>
		</table>
	</div>

	<div class="loading" id="loadingBar">
		<div class="timer-loader" style="margin-top:40%"></div>
	</div>

	<script src="components/jquery/dist/jquery.js?v=${buildTime}"></script>
    <script src="components/bootstrap/dist/js/bootstrap.min.js?v=${buildTime}"></script>
    <script src="components/d3/d3.min.js?v=${buildTime}"></script>
    <script src="components/handlebars/handlebars.min.js?v=${buildTime}"></script>
	<script src="components/moment/moment-with-locales.min.js?v=${buildTime}"></script>
    
    <script>
		var oRef = {
			REQ_URL: "getAgentList.pinpoint",
			CONST_ALL: "all",
			fnTableTemplate : Handlebars.compile([
				'<tr>',
					'<td>{{{index}}}</td>',
					'<td>',
						'{{#if visible}}<a href="/#/main/{{{appName}}}@{{{serviceType}}}" target="_blank">{{{appName}}}</a>{{/if}}',
						'<td data-app-name="{{{appName}}}@{{{serviceType}}}">{{{hostName}}}</td>',
					'<td class="version">{{{version}}}</td>',
					'<td class="jvm">{{{jvm}}}</td>',
				'</tr>'
			].join("")),
			fnSelectTemplate: Handlebars.compile('<option value="{{{version}}}">{{{version}}} - {{{count}}}</option>'),
			$tbody: $("tbody"),
			$select: $("#filter-version")
		};


		$.ajax({
			url: oRef.REQ_URL,
			method: "GET",
			dataType: "json"
		}).done( function(data){ //, textStatue, jqXHR) {
			if ( typeof data["exception"] === "undefined" ) {
				var versionData = parseResultData(data);
				var jvmData = parseJvmResultData(data);

				sortData(versionData);
				sortData(jvmData);
				addToSelect(versionData);
				dashboard('#dashboard', versionData);
				dashboard('#jvmDashboard', jvmData);
				addToTable(data);
			} else {
				alert( data["exception"].message );
			}
			$("#loadingBar").hide();
		}).fail(function(jqXHR, textStatus, errorThrown) {});

		function addToTable( data ) {
			var totalIndex = 1;
			for (var appName in data ) {
				var aApplication = data[appName];
				$.each( aApplication, function( index, o ) {
					oRef.$tbody.append( oRef.fnTableTemplate({
						index: totalIndex++,
						version: o.agentVersion,
						jvm: o.vmVersion,
						appName: appName,
						visible: index > 0 ? "" : appName,
						hostName: o.hostName,
						serviceType: o.serviceType
					}));
				});
			}
		}

		function addToSelect( data ) {
			var sum = 0;
			$.each( data, function(index, o ) {
				sum += o.count;
				oRef.$select.append( oRef.fnSelectTemplate(o) );
			});
			oRef.$select.find("option:first").html( "All - " + sum).end().on("change", function() {
				filterTable( $(this).val() );
			});
		}

		function sortData( data ) {
			data.sort( function( pre, cur ) {
				return pre.version > cur.version ? 1 : pre.version == cur.version ? 0 : -1;
			});
		}

		function filterTable( version ) {
			var newIndex = 1;
			oRef.$tbody.find("td.version").each(function() {
				var $this = $(this);
				if ( oRef.CONST_ALL == version || $this.html() === version ) {
					$this.parent().show();
					$this.parent().find("td:first").html(newIndex++);
				} else {
					$this.parent().hide();
				}
			});
		}

		function parseResultData( oData ) {
			var oResult = {};

			for (var p in oData ) {
				var a = oData[p];
				for( var j = 0 ; j < a.length ; j++ ) {
					var version = a[j].agentVersion;
					if ( typeof oResult[version] === "undefined" ) {
						oResult[version] = 1;
					} else {
						oResult[version]++;
					}
				}
			}
			var aResult = [];
			for(var ver in oResult ) {
				aResult.push({
					version: ver,
					count: oResult[ver]
				});
			}
			return aResult;
		}
		function parseJvmResultData( oData ) {
			var oResult = {};

			for (var p in oData ) {
				var a = oData[p];
				for( var j = 0 ; j < a.length ; j++ ) {
					var version = a[j].vmVersion;
					if ( typeof oResult[version] === "undefined" ) {
						oResult[version] = 1;
					} else {
						oResult[version]++;
					}
				}
			}
			var aResult = [];
			for(var ver in oResult ) {
				aResult.push({
					version: ver,
					count: oResult[ver]
				});
			}
			return aResult;
		}

		function dashboard(id, fData){
			var segColor = d3.scale.category20();

			function pieChart(pD){
				var pC = {};
				var pieDim = {
					w: 250,
					h: 250
				};
				pieDim.r = Math.min(pieDim.w, pieDim.h) / 2;

				var piesvg = d3.select(id).append("svg")
						.attr("width", pieDim.w).attr("height", pieDim.h).append("g")
						.attr("transform", "translate("+pieDim.w/2+","+pieDim.h/2+")");

				var arc = d3.svg.arc().outerRadius(pieDim.r - 10).innerRadius(0);
				var pie = d3.layout.pie().sort(null).value(function(d) { return d.count; });

				piesvg.selectAll("path").data(pie(pD)).enter().append("path").attr("d", arc)
						.each(function(d) { this._current = d; })
						.style("fill", function(d, i) { return segColor(i); });

				pC.update = function(nD){
					piesvg.selectAll("path").data(pie(nD)).transition().duration(500).attrTween("d", arcTween);
				};
				function arcTween(a) {
					var i = d3.interpolate(this._current, a);
					this._current = i(0);
					return function(t) { return arc(i(t));    };
				}
				return pC;
			}

			function legend(lD, selected){
				var leg = {};

				var legend = d3.select(id).append("table").attr('class','legend');
				var select = legend.append("thead").append("tr").append("td").attr("colspan", 4).append("select").attr("class", "form-control").attr("id", "chart-sort");
				select.append("option").attr("value", "version").text("Version");
				var optionCount = select.append("option");
				optionCount.attr("value", "count").text("Percentage");
				if ( selected == "count" ) {
					optionCount.attr("selected", "selected");
				}

				var tr = legend.append("tbody").selectAll("tr").data(lD).enter().append("tr");
				tr.append("td").append("svg").attr("width", '16').attr("height", '16').append("rect")
						.attr("width", '16').attr("height", '16')
						.attr("fill",function(d, i){ return segColor(i); });
				tr.append("td").text(function(d){ return d.version;});
				tr.append("td").attr("class",'legendFreq').text(function(d){ return d3.format(",")(d.count);});
				tr.append("td").attr("class",'legendPerc').text(function(d){ return getLegend(d,lD);});

				leg.update = function(nD){
					var l = legend.select("tbody").selectAll("tr").data(nD);
					l.select(".legendFreq").text(function(d){ return d3.format(",")(d.count);});
					l.select(".legendPerc").text(function(d){ return getLegend(d,nD);});
				}

				function getLegend(d,aD){
					return d3.format("%")(d.count/d3.sum(aD.map(function(v){ return v.count; })));
				}

				return leg;
			}
			pieChart(fData);
			legend(fData, "version");

			$(id).on("change", "select", function() {
				var key = $(this).val();
				fData.sort( function( pre, cur ) {
					$(id).empty();
					if ( key == "version") {
						return pre.version > cur.version ? 1 : pre.version == cur.version ? 0 : -1;
					} else {
						return cur.count > pre.count ? 1 : cur.count == pre.count ? 0 : -1;
					}
				});
				pieChart(fData);
				legend(fData, key);
			});
		}
	</script>
</body>
</html>
